package com.zengdada.authority.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.zengdada.authority.config.security.intercept.AuthorityUtil;
import com.zengdada.authority.config.security.intercept.MyFilterInvocationSecurityMetadataSource;
import com.zengdada.authority.exception.RoutineException;
import com.zengdada.authority.model.AppPower;
import com.zengdada.authority.model.AppUser;
import com.zengdada.authority.service.AppPowerAuthorityService;
import com.zengdada.authority.utils.JsonMessage;
import com.zengdada.authority.utils.mapper.Page;
import com.zengdada.authority.utils.mapper.Sort;
import com.zengdada.authority.utils.where.Where;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zengdada.authority.utils.JsonMessage.fail;
import static com.zengdada.authority.utils.JsonMessage.success;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2018/12/4 22:01
 * @Description:
 */
@Controller
@RequestMapping("/authority/power")
public class AppPowerAuthorityController {

    @Autowired
    AuthorityUtil authorityUtil;

    @Autowired
    @Qualifier("appPowerAuthorityServiceImpl")
    AppPowerAuthorityService appPowerAuthorityService;

    @Autowired
    private MyFilterInvocationSecurityMetadataSource securityMetadataSource;

    @GetMapping("/page.html")
    public String page() {
        return "authority/power/power";
    }

    @RequestMapping(value = "/power_tree.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage power_tree() {
        try {
            return success(appPowerAuthorityService.getPowerTree());
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }


    @RequestMapping(value = "/list.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage list(@RequestParam(value = "id", defaultValue = "") String id, String searchs, Page page, Sort sort) {
        try {
            List<Where> params = new ArrayList<>();
            Where where = new Where(Where.Formula.AND, params);
            try {
                params.add( Where.formJsonString(StringEscapeUtils.unescapeHtml4(searchs)));
            } catch (Exception e) {
                throw new RoutineException("查询条件解析失败：" + e.getMessage());
            }
            Where search = new Where();
            if ("".equals(id)) {
                search.setField("id");
                search.setFormulaE(Where.Formula.IN);
                List<String> collect = appPowerAuthorityService.getPowerTree().stream().map(i -> (String) i.get("id")).collect(Collectors.toList());
                search.setValue(JSON.toJSONString(collect));
            } else {
                search.setField("parentId");
                search.setFormulaE(Where.Formula.EQUAL);
                search.setValue(id);
            }
            params.add(search);
            PageInfo<Map<String, Object>> appPowerPageInfo = appPowerAuthorityService.selectDetailedPageInfoByParam(where, page, sort);
            return success(appPowerPageInfo.getList(), appPowerPageInfo.getTotal());
        } catch (Exception e) {

            return fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/detailed.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage detailed(@RequestParam(value = "id", defaultValue = "") String id) {
        try {
            AppPower appPower = appPowerAuthorityService.selectById(id);
            if (appPower == null) throw new RoutineException("未查询到相关信息");
            return success(appPower);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/del.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage del(@RequestParam(value = "id", defaultValue = "") String id) {
        try {
            if (appPowerAuthorityService.deleteById(id) == 0) throw new RoutineException("没有删除任何数据！！");
            securityMetadataSource.initOrUpdateMap();
            return success();
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage add(AppPower power) {
        try {
            AppUser user = authorityUtil.getLoginUser();
            if (StringUtils.isBlank(power.getId())) {
                power.setCreateUser(user.getId());
                if (appPowerAuthorityService.add(power) == 0) throw new RoutineException("新增失败！！");
            } else {
                power.setModifyUser(user.getId());
                power.setModifyTime(new Date());
                if (appPowerAuthorityService.updateById(power) == 0) throw new RoutineException("没有修改任何数据！！");
            }
            if (power.getIntercept() == null || power.getIntercept() == 0) securityMetadataSource.initOrUpdateMap();
            return success();
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

}
